package com.ctgu.chatapp.view

import android.os.Bundle
import android.os.Handler
import android.os.Looper
import android.os.Message
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.navigation.navArgs
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout
import com.ctgu.chatapp.R
import com.ctgu.chatapp.Service.RequestService
import com.ctgu.chatapp.databinding.ActivityFriendChatBinding
import com.ctgu.chatapp.model.Database.DataBaseManager
import com.ctgu.chatapp.model.pojo.RecordNew
import com.ctgu.chatapp.utils.Utils
import com.ctgu.chatapp.view.adapter.RecordAdapter
import com.ctgu.chatapp.viewModel.ChatViewModel
import com.google.android.material.snackbar.Snackbar
import kotlinx.coroutines.Dispatchers.IO
import kotlinx.coroutines.Dispatchers.Main
import kotlinx.coroutines.async
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext

class FriendChat : BaseActivity() {

    lateinit var binding: ActivityFriendChatBinding

    private val args: FriendChatArgs by navArgs()

    val dataBase = DataBaseManager.getInstance(this)

    var timeStamp = 0L

    val viewModel by lazy {
        ViewModelProvider(
            this,
            ViewModelProvider.AndroidViewModelFactory.getInstance(application)
        )[ChatViewModel::class.java]
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        println(Utils.friendID)
        binding = DataBindingUtil.setContentView(this, R.layout.activity_friend_chat)
        viewModel.friend = args.friend
        viewModel.chatID = args.chatID
        viewModel.profile = args.profile
        binding.viewModel = viewModel
        binding.friend = viewModel.friend
        initAdapter()
        setListener()
        binding.lifecycleOwner = this
        ActivityCollector.addActivity(this, this.javaClass);
    }

    private fun initAdapter() {
        adapter = RecordAdapter(mutableListOf(), viewModel.friend.profile, viewModel.profile)
        val layout = LinearLayoutManager(this)
        layout.orientation = LinearLayoutManager.VERTICAL
        binding.chatRecycleView.layoutManager = layout
        binding.chatRecycleView.adapter = adapter
        lifecycleScope.launch(IO) {
            val list = viewModel.recordList.toMutableList()
            list.reverse()
            adapter.addAll(list.toMutableList())
            binding.chatRecycleView.scrollToPosition(adapter.recordList.size)
        }
    }

    private fun setListener() {
        binding.sendBtn.setOnClickListener {
            if (!viewModel.inputText.value.isNullOrEmpty()) {
                val message = RecordNew(
                    System.currentTimeMillis(),
                    viewModel.chatID,
                    viewModel.friend.chatID,
                    0,
                    viewModel.inputText.value!!,
                    System.currentTimeMillis(),
                    true
                )
                adapter.addMessage(message)
                RequestService.sendChatRequest(
                    viewModel.chatID,
                    viewModel.friend.chatID,
                    binding.editText2.text.toString()
                )
                lifecycleScope.launch(IO) {
                    viewModel.inputText.postValue("")
                }
            }
        }
        binding.swipe.setOnRefreshListener {
            lifecycleScope.launch(Main) {
                if (adapter.recordList.isNotEmpty()) {
                    timeStamp = adapter.recordList[0].date
                    val list = async(IO) {
                        dataBase.getMsgDao()
                            .getOldRecord(viewModel.chatID, viewModel.friend.chatID, timeStamp)
                    }
                    addOldRecord(list.await(), binding.swipe)
                } else {
                    Snackbar.make(binding.swipe, "您与他还没有消息哦", Snackbar.LENGTH_SHORT).show()
                    binding.swipe.isRefreshing = false
                }
            }
        }
    }

    private suspend fun addOldRecord(list: List<RecordNew>, view: SwipeRefreshLayout) {
        withContext(Main) {
            if (list.isEmpty()) {
                Snackbar.make(view, "消息到顶了哦", Snackbar.LENGTH_SHORT).show()
            } else {
                val reverse = list.toMutableList()
                reverse.reverse()
                adapter.addOldRecord(reverse)
                timeStamp = adapter.recordList[0].date
            }
            binding.swipe.isRefreshing = false
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        println("触发")
        Utils.friendID = 0
    }

    companion object {
        lateinit var adapter: RecordAdapter

        val handler = object : Handler(Looper.myLooper()!!) {
            override fun handleMessage(msg: Message) {
                super.handleMessage(msg)
                when (msg.what) {
                    0 -> {
                        for (i in adapter.recordList.size..0) {
                            if (adapter.recordList[i].id == msg.obj as Long) {
                                adapter.recordList[i].state.postValue(0)
                            }
                        }
                    }
                    1 -> {
                        val recordNew = msg.obj as RecordNew
                        if (recordNew.friendID == Utils.friendID)
                            adapter.addMessage(msg.obj as RecordNew)
                    }
                    2 -> {
                        val recordNew = msg.obj as com.ctgu.chatapp.Netty.protocol.Message.IMSMsg
                        if (recordNew.head.fromId == Utils.friendID) {
                            adapter.removeMessage(recordNew.chatRequest.snowFlower)
                            adapter.notifyItemRangeChanged(0, adapter.itemCount)
                        }
                    }
                    3 -> {
                        val id = msg.obj as com.ctgu.chatapp.Netty.protocol.Message.IMSMsg
                        adapter.setID(id.chatAck.id, id.head.timestamp)
                    }
                    else -> {}
                }
            }
        }
    }

}